import sun.font.CreatedFontTracker;

import java.util.*;

public class BinaryTree {
    static class TreeNode {
        public char val;
        public TreeNode right;// 右孩子的引用，常常代表右孩子为根的整棵右子树
        public TreeNode left;//左孩子的引用，常常代表左孩子为根的整棵左子树

        public TreeNode(char val) {
            this.val = val;
        }
    }


    public TreeNode root;//这个引用指向根节点


    public TreeNode createTree() {
        TreeNode A = new TreeNode('A');
        TreeNode B = new TreeNode('B');
        TreeNode C = new TreeNode('C');
        TreeNode D = new TreeNode('D');
        TreeNode E = new TreeNode('E');
        TreeNode F = new TreeNode('F');
        TreeNode G = new TreeNode('G');
        TreeNode H = new TreeNode('H');
        A.left = B;
        A.right = C;
        B.left = D;
        B.right = E;
        C.left = F;
        C.right = G;
        E.right = H;
        return A;
    }


    //前序遍历 根 左 右
    public void preOrder(TreeNode root) {
        if (root == null) {
            return;
        }
        System.out.print(root.val + " ");
        preOrder(root.left);
        preOrder(root.right);
    }

    //将前序遍历的返回值存到List中
    public List<TreeNode> preOrder2(TreeNode root) {

        List<TreeNode> list = new ArrayList<>();
        if (root == null) {
            return list;
        }
        list.add(root);
        List<TreeNode> leftTree = preOrder2(root.left);
        list.addAll(leftTree);
        List<TreeNode> rightTree = preOrder2(root.right);
        list.addAll(rightTree);

        return list;
    }


    //中序遍历 左 根 右
    public void inOrder(TreeNode root) {
        if (root == null) return;
        inOrder(root.left);
        System.out.print(root.val + " ");
        inOrder(root.right);
    }

    //中序遍历的返回值存到List中
    public List<TreeNode> inOrder2(TreeNode root) {
        List<TreeNode> list = new ArrayList<>();
        if (root == null) return list;

        List<TreeNode> leftTree = inOrder2(root.left);
        list.addAll(leftTree);

        list.add(root);

        List<TreeNode> rightTree = inOrder2(root.right);
        list.addAll(rightTree);
        return list;
    }

    //后序遍历 左 右 根
    public void postOrder(TreeNode root) {
        if (root == null) return;
        postOrder(root.left);
        postOrder(root.right);
        System.out.print(root.val + " ");
    }

    //后序遍历的返回值存到List中
    public List<TreeNode> postOrder2(TreeNode root) {
        List<TreeNode> list = new ArrayList<>();
        if (root == null) return list;

        List<TreeNode> leftTree = postOrder2(root.left);
        list.addAll(leftTree);

        List<TreeNode> rightTree = postOrder2(root.right);
        list.addAll(rightTree);

        list.add(root);

        return list;
    }


    //前序遍历方式获取树中节点的个数

    public int nodeSize(TreeNode root) {
        int size = 0;
        if (root == null) return 0;
        size++;
        size += nodeSize(root.left);
        size += nodeSize(root.right);

        return size;
    }

    public int size = 0;

    public void nodeSize2(TreeNode root) {
        if (root == null) return;
        size++;
        nodeSize2(root.left);
        nodeSize2(root.right);
    }


    public int nodeSize3(TreeNode root) {
        if (root == null) return 0;
        return nodeSize3(root.left) + nodeSize3(root.right) + 1;
    }


    // 获取叶子节点的个数
    public static int leafSize = 0;

    public int getLeafSize(TreeNode root) {
        if (root == null) return 0;

        if (root.left == null && root.right == null) {
            leafSize++;
        }
        getLeafSize(root.left);
        getLeafSize(root.right);
        return leafSize;
    }


    public int getLeafSize2(TreeNode root) {
        if (root == null) return 0;
        if (root.left == null && root.right == null) {
            return 1;
        }
        return getLeafSize2(root.left) + getLeafSize2(root.right);
    }


    // 获取第K层节点的个数
    public int getKLevelNodeCount(TreeNode root, int k) {
        if (root == null) return 0;
        if (k == 1) {
            return 1;
        }
        return getKLevelNodeCount(root.left, k - 1) + getKLevelNodeCount(root.right, k - 1);
    }


    // 获取二叉树的高度
    int getHeight(TreeNode root) {
        if (root == null) return 0;

        int leftHeight = getHeight(root.left);
        int rightHeight = getHeight(root.right);
        if (leftHeight > rightHeight) {
            return leftHeight + 1;
        }
        return rightHeight + 1;
    }


    // 检测值为value的元素是否存在
    public TreeNode find(TreeNode root, char val) {
        if (root == null) return null;

        if (root.val == val) {
            return root;
        }

        TreeNode leftVal = find(root.left, val);
        if (leftVal != null) {
            return leftVal;
        }
        TreeNode rightVal = find(root.right, val);
        if (rightVal != null) {
            return rightVal;
        }

        return null;
    }


    public boolean find2(TreeNode root, char val) {
        if (root == null) return false;

        if (root.val == val) {
            return true;
        }

        boolean leftVal = find2(root.left, val);
        if (leftVal == true) {
            return true;
        }
        boolean rightVal = find2(root.right, val);
        if (rightVal == true) {
            return true;
        }

        return false;
    }


    //判断两棵树是否相等
    public boolean isSameTree(TreeNode p, TreeNode q) {
        if (p == null && q != null || q == null && p != null) {
            return false;
        }
        //两个都为空
        if (p == null && q == null) {
            return true;
        }
        //两个都不为空
        if (p.val != q.val) {
            return false;
        }
        return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
    }

    //另一颗树的子树
    public boolean isSubtree(TreeNode root, TreeNode subRoot) {
        if (root == null) {
            return false;
        }
        if (isSameTree(root, subRoot)) {
            return true;
        }
        return isSubtree(root.left, subRoot) || isSubtree(root.right, subRoot);
    }


    public boolean isSubtree2(TreeNode root, TreeNode subRoot) {
        if (root == null) return false;

        if (isSameTree(root, subRoot)) {
            return true;
        }
        if (isSubtree2(root.left, subRoot)) {
            return true;
        }
        if (isSubtree2(root.right, subRoot)) {
            return true;
        }
        return false;
    }


    //平衡二叉树 有许多不必要的计算和递归调用
    public boolean isBalanced(TreeNode root) {
        if (root == null) return false;
        int leftHeight = getHeight(root.left);
        int rightHeight = getHeight(root.right);
        if (Math.abs(leftHeight - rightHeight) <= 1 && isBalanced(root.left) && isBalanced(root.right)) {
            return true;
        }

        return false;
    }


    //获取节点的高度
    int getHeight2(TreeNode root) {
        if (root == null) return 0;

        int leftHeight = getHeight(root.left);
        int rightHeight = getHeight(root.right);
        //这里求过程中每一个子树的高度，一旦有不平衡的就返回-1
        //(leftHeight >= 0 && rightHeight >= 0是因为左右两边都可能返回-1
        if (leftHeight >= 0 && rightHeight >= 0 && Math.abs(leftHeight - rightHeight) <= 1) {
            return Math.max(leftHeight, rightHeight) + 1;
        } else {
            return -1;
        }
    }

    public boolean isBalanced2(TreeNode root) {
        if (root == null) return true;
        return getHeight2(root) >= 0;
    }


    //对称二叉树
    public boolean isSymmetric(TreeNode root) {
        if (root == null) {
            return true;
        }
        return isSymmetricChild(root.left, root.right);
    }


    public boolean isSymmetricChild(TreeNode p, TreeNode q) {
        if (p == null && q != null || q == null && p != null) {
            return false;
        }
        if (p == null && q == null) {
            return true;
        }
        if (p.val != q.val) {
            return false;
        }

        return isSymmetricChild(p.left, q.right) && isSymmetricChild(p.right, q.left);
    }


    //分层遍历 迭代
    public void levelOrder1(TreeNode root) {
        if (root == null) {
            return;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            TreeNode cur = queue.poll();
            System.out.print(cur.val + " ");
            if (cur.left != null) {
                queue.offer(cur.left);
            }
            if (cur.right != null) {
                queue.offer(cur.right);
            }
        }

    }


    public List<List<Integer>> levelOrder2(TreeNode root) {
        List<List<Integer>> ret = new ArrayList<>();
        if (root == null) {
            return ret;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            //计算当前队列有多少个元素，相当于要往当前行添加多少元素，就要出多少次队列
            List<Integer> tmp = new ArrayList<>();
            int size = queue.size();
            for (int j = 0; j < size; j++) {
                TreeNode cur = queue.poll();
                tmp.add((int) cur.val);

                if (cur.left != null) {
                    queue.offer(cur.left);
                }
                if (cur.right != null) {
                    queue.offer(cur.right);
                }

            }
            ret.add(tmp);

        }
        return ret;
    }


    //递归调用 分层遍历
    public List<List<Integer>> levelOrder3(TreeNode root) {
        List<List<Integer>> ret = new ArrayList<>();
        traverse(root, 0, ret);
        return ret;
    }

    private void traverse(TreeNode root, int level, List<List<Integer>> ret) {
        if (root == null) {
            return;
        }
        if (ret.size() <= level) {
            ret.add(new ArrayList<>());
        }

        ret.get(level).add((int) root.val);
        traverse(root.left, level + 1, ret);
        traverse(root.right, level + 1, ret);
    }


    //求完全二叉树的最宽的宽度
    public int widestLevel(TreeNode root) {
        if (root == null) {
            return 0;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        int maxWidth = 0;

        while (!queue.isEmpty()) {
            int size = queue.size();
            maxWidth = Math.max(size, maxWidth);

            for (int j = 0; j < size; j++) {
                TreeNode cur = queue.poll();
                if (cur.left != null) {
                    queue.offer(cur.left);
                }
                if (cur.right != null) {
                    queue.offer(cur.right);
                }

            }
        }
        return maxWidth;
    }


    //判断一棵树是不是完全二叉树
    public boolean isCompleteTree(TreeNode root) {
        if (root == null) {
            return true;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            TreeNode cur = queue.poll();
            if (cur != null) {
                queue.offer(cur.left);
                queue.offer(cur.right);
            } else {
                //证明遇到了null
                break;
            }
        }
        while (!queue.isEmpty()) {
            TreeNode cur = queue.poll();
            if (cur != null) {
                return false;
            }
        }
        return true;
    }


    // 1.给定一个二叉树, 找到该树中两个指定节点的最近公共祖先
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if (root == null) {
            return null;
        }
        if (p == root || q == root) {
            return root;
        }
        TreeNode leftTree = lowestCommonAncestor(root.left, p, q);
        TreeNode rightTree = lowestCommonAncestor(root.right, p, q);

        if (leftTree != null && rightTree != null) {
            return root;
        } else if (leftTree != null) {
            return leftTree;
        } else {
            return rightTree;
        }

    }


    // 2.给定一个二叉树, 找到该树中两个指定节点的最近公共祖先

    /**
     *找到root 到 node 之间路径上 的 所有 的 节点 存储到stack中
     * @param root
     * @param node
     * @param stack
     * @return
     */
    private boolean getPath(TreeNode root, TreeNode node, Stack<TreeNode> stack) {
        if (root == null || node == null) {
            return false;
        }
        stack.push(root);
        if (root == node) {
            return true;
        }
        boolean flg = getPath(root.left, node, stack);
        if (flg == true) {
            return true;
        }
        boolean flg2 = getPath(root.right, node, stack);
        if (flg2 == true) {
            return true;
        }
        stack.pop();
        return false;
    }


    public TreeNode lowestCommonAncestor2(TreeNode root, TreeNode p, TreeNode q) {
        if (root == null) {
            return null;
        }
        Stack<TreeNode> stackP = new Stack<>();
        Stack<TreeNode> stackQ = new Stack<>();

        getPath(root, p, stackP);
        getPath(root, q, stackQ);

        int sizeP = stackP.size();
        int sizeQ = stackQ.size();
        if (sizeP - sizeQ > 0) {
            int size = sizeP - sizeQ;
            while (size != 0) {
                stackP.pop();
                size--;
            }
        } else {
            int size = sizeQ - sizeP;
            while (size != 0) {
                stackQ.pop();
                size--;
            }
        }
        while (stackP != null && stackQ != null) {
            if (stackP.peek().equals(stackQ.peek())) {
                return stackQ.peek();
            }
            stackP.pop();
            stackQ.pop();
        }
        return null;
    }




    //根据一棵树的前序遍历与中序遍历构造二叉树。
    class Solution {
        public int priIndex;
        public TreeNode buildTree(int[] preorder, int[] inorder) {


            return buildTreeChild(preorder,inorder,0,inorder.length-1);
        }

        private TreeNode buildTreeChild(int[] preorder, int[] inorder, int inbegin, int inend) {

            //1. 没有左树 或者 没有右树了
            if(inbegin > inend) {
                return null;
            }
            //2.创建根节点
            TreeNode root = new TreeNode((char) preorder[priIndex]);

            //3.从中序遍历当中 找到根节点所在的下标
            int rootIndex = findIndex(inorder,inbegin,inend,preorder[priIndex]);
            if(rootIndex == -1){
                return null;
            }
            priIndex++;
            //4. 创建左子树 和  右子树
            root.left = buildTreeChild(preorder,inorder,inbegin,rootIndex-1);
            root.right = buildTreeChild(preorder,inorder,rootIndex+1,inend);

            return root;
        }


        private int findIndex(int[] inorder,int inbegin,int inend,int key) {
            for (int i = inbegin; i <= inend; i++) {
                if(inorder[i] == key){
                    return i;
                }
            }
            return -1;
        }

    }



    // 二叉树创建字符串
    public String tree2str(TreeNode root) {
        StringBuilder stringBuilder  = new StringBuilder();
        tree2strChild(root,stringBuilder);
        return stringBuilder.toString();
    }

    private void tree2strChild(TreeNode t,StringBuilder stringBuilder) {
        if(t == null){
            return;
        }
        stringBuilder.append(t.val);

        //左边为空和左边不为空的情况
        if(t.left != null){
            stringBuilder.append("(");
            tree2strChild(t.left,stringBuilder);
            stringBuilder.append(")");
        }else {
            if(t.right != null){
                stringBuilder.append("()");
            }else {
                return;
            }
        }

        //右边为空和右边不为空的情况
        if(t.right != null){
            stringBuilder.append("(");
            tree2strChild(t.right,stringBuilder);
            stringBuilder.append(")");
        }else {
            return;
        }
    }




    // 用栈实现二叉树前序非递归遍历实现
    public void preOrderNor(TreeNode root) {
        if(root == null){
            return;
        }
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        TreeNode top = null;
        while (cur != null || !stack.isEmpty()) {
            while (cur != null) {
                stack.push(cur);
                System.out.print(cur.val + " ");
                cur = cur.left;
            }
            top = stack.pop();
            cur = top.right;
        }
    }

    public List<Integer> preorderTraversal(TreeNode root) {
        if(root == null){
            return new ArrayList<>();
        }
        List<Integer> list = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        TreeNode top = null;
        while (cur != null || !stack.isEmpty()) {
            while (cur != null) {
                stack.push(cur);
                list.add((int) cur.val);
                cur = cur.left;
            }
            top = stack.pop();
            cur = top.right;
        }
        return list;
    }


    //实现二叉树中序非递归遍历实现
    public List<Integer> inorderTraversal(TreeNode root) {
        if(root == null){
            return new ArrayList<>();
        }
        List<Integer> list = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        TreeNode top = null;
        while (cur != null || !stack.isEmpty()) {
            while (cur != null) {
                stack.push(cur);
                cur = cur.left;

            }
            top = stack.pop();
            list.add((int) top.val);
            cur = top.right;
        }
        return list;
    }


    public void inOrderNor(TreeNode root) {
        if(root == null) return;
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        TreeNode top = null;
        while (cur != null || !stack.isEmpty()) {
            while (cur != null) {
                stack.push(cur);
                cur = cur.left;
            }
            top = stack.pop();
            System.out.print(top.val + " ");
            cur = top.right;
        }
    }


    ////实现二叉树后序非递归遍历实现
    public void postOrderNor(TreeNode root) {
        if (root == null) return;
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        TreeNode top = null;
        TreeNode prev = null;
        while (cur != null || !stack.isEmpty()) {
            while (cur != null) {
                stack.push(cur);
                cur = cur.left;
            }
            top = stack.peek();

            if (top.right == null || top.right == prev) {
                stack.pop();
                System.out.print(top.val + " ");
                prev = top;//当前这个节点被打印了
            }else {
                cur = top.right;
            }
        }
    }

    public List<Integer> postorderTraversal(TreeNode root) {
        if(root == null){
            return new ArrayList<>();
        }
        List<Integer> list = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        TreeNode top = null;
        TreeNode prev = null;
        while (cur != null || !stack.isEmpty()) {
            while (cur != null) {
                stack.push(cur);
                cur = cur.left;
            }
            top = stack.peek();

            if (top.right == null || top.right == prev) {
                stack.pop();
                list.add((int) top.val);
                prev = top;//当前这个节点被打印了
            }else {
                cur = top.right;
            }
        }
        return list;
    }

}
